import React, { Component } from 'react';
import { Button, Modal, Form, Drawer, Alert, Divider, Icon, Badge } from 'antd';
import '@/assets/css/settings';
import * as ProductionOrderService from '../../../axios/ProductionOrder'
import * as ProcessQualityControlService from '../../../axios/ProcessQualityControl'
import * as APIServiceYQ from '../../../axios/api_yq'
import * as APIService from '../../../axios/api'
import { BasicLayout, BasicLayoutSearch } from '../../../components/BasicLayout';
import { BasicPagination, isInvalidObject, TableCustomize, openSuccessModal, openModalMessage, compareDate, compareString } from '../../../components/TableCustomize'
import { withPermission } from '../../../components/withpermission';
import { statusList, checkResultList } from '../../../utils/global';

import ChooseBill from './ChooseBill';
import { withRouter } from 'react-router';
const CreateButton = withPermission(Button, 'create')

class SelfChecking extends Component {
  state = {
    dataSource: [],
    visibleChooseBill: false,
    advanced: false,
    searchItem: {
      department: localStorage.getItem('workShop')
    },
    formData: {},
    pageSize: 10,
    pageNum: 1,
    total: 0,
    statusList: [],
    columns: [
      {
        title: '序号',
        dataIndex: 'dataIndex',
        width: 50,
        align: 'center',
        render: (text, record, index) => <span>{(this.state.pageNum - 1) * (this.state.pageSize) + index + 1}</span>
      },
      {
        title: '批号',
        dataIndex: 'batchNo',
        width: 100,
        sorter: (a, b) => compareString(a.batchNo, b.batchNo)
      },

      {
        title: '机型',
        width: 180,
        dataIndex: 'model',
        sorter: (a, b) => compareString(a.model, b.model),
        // editable: true
      },
      {
        title: '适用工序',
        width: 150,
        // allowEllipsis: true,
        dataIndex: 'procedureName',
        sorter: (a, b) => compareString(a.procedureName, b.procedureName)
      },
      {
        title: '工序编码',
        width: 100,
        // allowEllipsis: true,
        dataIndex: 'procedureCode',
        sorter: (a, b) => compareString(a.procedureCode, b.procedureCode)
      },
      {
        title: '提交人',
        width: 100,
        // allowEllipsis: true,
        dataIndex: 'submitName',
        sorter: (a, b) => compareString(a.submitName, b.submitName)
      },
      {
        title: '班组长',
        width: 100,
        dataIndex: 'leaderName',
        sorter: (a, b) => compareString(a.leaderName, b.leaderName),
      },
      {
        title: '创建时间',
        width: 150,
        dataIndex: 'createTime',
        ellipsis: true,
        sorter: (a, b) => compareDate(a.createTime, b.createTime)
      },
      {
        title: '结果',
        width: 100,
        dataIndex: 'checkResult',
        sorter: (a, b) => compareString(a.checkResult, b.checkResult),
        render: (text, record, index) => {
          let a = checkResultList.find(item => item.id == text)
          return a.id == '0' ? <Badge color='#1890ff' text={<span style={{ color: '#1890ff' }}>{a.value}</span>} />
            : a.id == '1' ? <Badge status="success" text={<span style={{ color: '#1e8e3e' }}>{a.value}</span>} />
              : a.id == '2' ? <Badge status="error" text={<span style={{ color: '#f00' }}>{a.value}</span>} />
                : a.value
        }
      },
      {
        title: '操作',
        width: 100,
        dataIndex: 'opts',
        render: (text, record) => <>
          <a onClick={() => this.edit(record)}>详情/编辑</a>
        </>
      },
      { dataIndex: '' }
    ],
    selectedRows: [],
    selectedRowKeys: [],
    btnLoading: false,
  };
  componentDidMount() {
    this.props.onRef(this)

    this.setState({ statusList })
  }

  getSelectedRows = () => {
    const { selectedRows, selectedRowKeys } = this.state
    return { selectedRows, selectedRowKeys }
  }

  // 点击查询按钮
  getSearchItem = (data) => {
    this.setState({ searchItem: data }, this.fetch)
  }

  //初始化加载数据
  fetch = (pageNum = 1, pageSize = 10) => {
    this.setState({ loading: true })
    const { searchItem } = this.state
    searchItem.pageNum = pageNum
    searchItem.pageSize = pageSize

    ProcessQualityControlService.findFromCheck(searchItem).then(res => {
      this.setState({ loading: false })
      if (res.data.data.code !== 200) {
        openModalMessage('warning', res.data.data.msg)
        return
      }
      this.setState({ dataSource: res.data.data.data, total: res.data.data.total, pageNum, pageSize })
    }).catch(err => {
      openModalMessage('error', err.message)
    })
  }

  handleCancel = e => {
    this.formChooseBill && this.formChooseBill.resetFields();
    this.setState({
      visibleChooseBill: false,
      selectedRowKeys: [],
      selectedRows: [],
      btnLoading: false
    });
    this.fetch();
  };

  loadData = (value, dataSource) => {
    console.log(value, dataSource)
  }
  // 选择某一行数据
  chooseRow = record => {
    let flag = true;
    let index = 0;
    this.state.selectedRowKeys.forEach((row, i) => {
      if (row === record.id) {
        flag = false;
        index = i;
      }
    })
    const selectedRowKeys = this.state.selectedRowKeys;
    const selectedRows = this.state.selectedRows;
    if (flag) {
      selectedRowKeys.push(record.id);
      selectedRows.push(record);
    } else {
      selectedRowKeys.splice(index, 1);
      selectedRows.splice(index, 1);
    }
    this.setState({ selectedRowKeys: selectedRowKeys, selectedRows: selectedRows });
  };
  chooseBill = () => {
    this.setState({ visibleChooseBill: true })
  }

  //详情/编辑
  edit = (record) => {
    this.openDetails(record)
  };
  // 打开详情页
  openDetails = (record) => {
    const { searchItem } = this.state
    let data = { searchItem, record }
    localStorage.setItem('SelfCheckingList', JSON.stringify(data))
    this.props.history.push({ pathname: "/SelfCheckingList", data })
  }
  render() {
    const { loading, dataSource, columns, pageNum, pageSize, total, selectedRowKeys, } = this.state;
    const rowSelection = {
      type: 'checkbox',
      selectedRowKeys: selectedRowKeys,
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRows: selectedRows,
          selectedRowKeys: selectedRowKeys,
        })
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        const keys = [... this.state.selectedRowKeys];
        const rows = [... this.state.selectedRows];
        if (selected) {
          changeRows.forEach(row => {
            if (isInvalidObject(keys.find(key => key === row.id))) {
              keys.push(row.id);
              rows.push(row);
            }
          })
        } else {
          changeRows.forEach(row => {
            keys.splice(keys.indexOf(row.id), 1);
            rows.splice(rows.indexOf(row), 1);
          })
        }
        this.setState({ selectedRows: rows, selectedRowKeys: keys })
      }
    }
    return (
      <div>
        <div>
          <Alert message={<div>已选择<span style={{ color: '#fd1818', margin: '0 3px' }}>{selectedRowKeys.length}</span>项</div>} type="info" showIcon style={{ marginBottom: 15 }} />
          <TableCustomize
            columns={columns}
            rowKey={(record) => record.id}
            dataSource={dataSource}
            pagination={false}
            loading={loading}
            allowDrafting={true}
            allowRowEdit
            allowEditable={this.loadData}
            rowSelection={rowSelection}
            onRow={(record, rowKey) => ({
              onClick: this.chooseRow.bind(this, record, rowKey)
            })}
            rowClassName={(record, index) => {
              return (['editable-row', index % 2 === 0 ? 'editable-row' : 'editable-row12'])
            }}
          />
          <BasicPagination pageNum={pageNum} pageSize={pageSize} total={total} loadData={this.fetch} />
        </div>
      </div>
    );
  }
}
export default Form.create()(withRouter(SelfChecking));